package com.yang.web.featuretest.config;

import com.auth0.jwt.interfaces.Claim;
import com.yang.web.featuretest.annotation.Login;
import com.yang.web.featuretest.constants.Constants;
import com.yang.web.featuretest.service.IAuthService;
import com.yang.web.featuretest.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.Map;
import java.util.concurrent.ConcurrentSkipListMap;

import static com.yang.web.featuretest.util.JWTUtil.decode;

/**
 * @Description:
 * @Author: yangzhiwei
 * @Date: 2021/8/31 17:12
 */
@Slf4j
@Component
@Service
public class GlobalInterceptor implements HandlerInterceptor {
    //    private static final Logger logger = LoggerFactory.getLogger(GlobalInterceptor.class);  //really invoke
    //
    @Autowired
    IAuthService iAuthService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            // 静态资源
            log.info("请求异常，非 HandlerMethod");
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        if (method.getMethodAnnotation(Login.class) == null) {
            return true;
        }
        // ** header字段固定属性
        String token = null;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(Constants.getJwtProperty())) {
                token = cookie.getValue();
            }
        }
        System.out.println(token);
        Map<String, Claim> claimMap = decode(token);
        System.out.println(iAuthService);
        if (token == null || !iAuthService.authentication(claimMap)) {
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
